package hot_100;

public class K个一组翻转链表 {
    public static void main(String[] args) {

    }


    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode p0 = head;
        int cnt = 0;
        while (p0 != null) {
            cnt++;
            p0 = p0.next;
        }
        cnt = cnt / k;

        ListNode ans = new ListNode();
        ans.next = head;
        p0 = ans;
        for (int i = 1; i <= cnt; i++) {
            ListNode pre = null;
            ListNode cur = p0.next;
            for (int j = 1; j <= k; j++) {
                ListNode temp = cur;
                cur = cur.next;
                temp.next = pre;
                pre = temp;
            }
            ListNode s = p0.next;
            p0.next.next = cur;
            p0.next = pre;
            p0 = s;
        }
        return ans.next;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
